/* 
 * Copyright (C) 2010 Christian Schneider
 * 
 * This file is part of NS2 news.
 * 
 * NS2 news is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NS2 news is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NS2 news.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package tritop.android.naturalselectionnews;

import java.util.Map.Entry;
import java.util.TreeMap;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class StatsVisualizer extends Activity implements IGLOBALS{
	public static final String VISVALUES = "VISVALUES";
	public static final String BUILDVERSION = "BUILDVERSION";
	
	private static final String LOGTAG="PieChart";
	private ContentValues mValues;
	private int buildVersion  = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		Bundle bundel= getIntent().getExtras();
		if(bundel != null){
			if(bundel.containsKey(VISVALUES)){
				mValues=bundel.getParcelable(VISVALUES);
			}
			else {
				mValues = new ContentValues();
			}
			if(bundel.containsKey(BUILDVERSION)){
				buildVersion=bundel.getInt(BUILDVERSION);
			}
		}
		setContentView(new PieVis(this));
		//TODO: generic chart title
		String msg = (buildVersion==0)?"Winning team":"Winning team build:"+buildVersion;
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

	public class PieVis extends View {

		private int mWidth,mHeight;
		private Paint mPaint;
		private int[] mColors={Color.BLUE,Color.RED,Color.CYAN,Color.GREEN,Color.MAGENTA,Color.YELLOW,Color.DKGRAY,Color.LTGRAY};
		private int mPieSize;
		private RectF mPieArea;
		
		
		public PieVis(Context context) {
			super(context);
			this.setBackgroundResource(R.drawable.shape_background_vis);
			mPaint = new Paint();
			mPaint.setAntiAlias(true);
	        mPaint.setStyle(Paint.Style.FILL);
	        calcSum(StatsVisualizer.this.mValues);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			//canvas.drawColor(Color.BLACK);
			mPaint.setColor(mColors[0]);
			mPaint.setTextSize(20);
			if(StatsVisualizer.this.mValues!=null){
				calcPieSize(StatsVisualizer.this.mValues,canvas, mPaint);
				drawUnderline(StatsVisualizer.this.mValues,canvas, mPaint);
			}
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			mWidth=w;
			mHeight=h;
			mPieSize=(mWidth>mHeight)?mHeight:mWidth;
			mPieArea= new RectF( 0, 0,  mPieSize, mPieSize);
		}
		
		private void calcPieSize(ContentValues values,Canvas canvas,Paint paint){
			int keySum=0;
			float curAngle=0.0f;
			int col=0;
			keySum=calcSum(values);
			for(Entry<String, Object> entry: values.valueSet()){
				float angle=((float)(Integer)entry.getValue()/keySum)*360;
				mPaint.setColor(mColors[col]);
				if(DEBUG_ON){
					Log.e(LOGTAG,"curAngle: "+curAngle+" angle"+angle);
				}
				//skip if < 5%
				if(angle>18){
					canvas.drawArc(mPieArea, curAngle, angle, true, mPaint);
					curAngle+=angle;
					col++;
				}
			}
			
			
		}
		
		private int calcSum(ContentValues values){
			int sum=0;
			for(Entry<String, Object> entry: values.valueSet()){
				sum+=(Integer)entry.getValue();
			}
			if(DEBUG_ON){
				Log.e(LOGTAG,"sum: "+sum);
			}
			return sum;
		}
		
		private void drawUnderline(ContentValues values,Canvas canvas,Paint paint){
			int PADDING=10;
			int sideA=Math.abs(mWidth-mHeight);
			int sideB=mPieSize+PADDING;
			int col=0;
			int keySum=0;
			keySum=calcSum(values);
			if(DEBUG_ON){
				Log.e(LOGTAG,"SideA: "+sideA+" sideB:"+sideB);
			}
			if(mHeight>mWidth){
				//Portrait
				float rowHeight=sideA/StatsVisualizer.this.mValues.size();
				float rowWidth=sideB/2;
				float x=PADDING,y=sideB+rowHeight;
				y-=rowHeight;
				for(Entry<String, Object> entry: values.valueSet()){
					//new Line after 2 Entries
					y+=(col%2==1)?0:rowHeight;
					mPaint.setColor(mColors[col]);
					if(DEBUG_ON){
						Log.e(LOGTAG,"1: X: "+x+" Y:"+y);
					}
					
					float percentage=(float)((Integer)entry.getValue())/keySum*100;
					if(Float.isNaN(percentage)){canvas.drawText("invalid data", x, y, paint);break;}
					canvas.drawText(String.format("%.1f", percentage)+"% "+entry.getKey(), x, y, paint);
					//switch between left and right column
					x=(x==rowWidth)?PADDING:rowWidth;
					col++;
				}
			}
			else{
				//Landscape
				float rowHeight=sideB/StatsVisualizer.this.mValues.size();
				float rowWidth=sideA/2;
				float x=sideB,y=rowHeight;
				y-=rowHeight;
				for(Entry<String, Object> entry: values.valueSet()){
					//new Line after 2 Entries
					y+=(col%2==1)?0:rowHeight;
					mPaint.setColor(mColors[col]);
					if(DEBUG_ON){
						Log.e(LOGTAG,"2: X: "+x+" Y:"+y);
					}
					float percentage=(float)((Integer)entry.getValue())/keySum*100;
					if(Float.isNaN(percentage)){canvas.drawText("invalid data", x, y, paint);break;}
					canvas.drawText(String.format("%.1f", percentage)+"% "+entry.getKey(), x, y, paint);
					//switch between left and right column
					x=(x==sideB)?sideB+rowWidth:sideB;
					col++;
				}
			}
		}
	}
}
